package com.seven.mybatisx.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.gs.cd.api.ApiResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

// TODO: 2020/12/28 查询排序问题
public abstract class AbstractController<T, V extends IService<T>> implements IController<T> {
    @Autowired
    protected V iService;


    /**
     * 添加or修改
     *
     * @param t
     * @return
     */
    @PutMapping("saveOrUpdate")
    @Override
    public ApiResult saveOrUpdate(@RequestBody T t) {
        boolean b = iService.saveOrUpdate(t);
        if (b) {
            return ApiResult.success(t);
        }
        System.out.println("保存失败：" + t);
        return ApiResult.error("操作失败");
    }

    /**
     * 批量保存
     */
    @PostMapping("save/more")
    @Override
    public ApiResult saveMore(@RequestBody List<T> t) {
        boolean b = iService.saveBatch(t);
        if (b) {
            return ApiResult.success(t);
        }
        System.out.println("保存失败：" + t);
        return ApiResult.error("操作失败");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @DeleteMapping("delete/{id}")
    @Override
    public ApiResult deleteById(@PathVariable Serializable id) {
        return iService.removeById(id) ? ApiResult.success() : ApiResult.error();
    }

    /**
     * 通过id 批量删除
     */
    @DeleteMapping("delete/more")
    @Override
    public ApiResult deleteMore(List<Serializable> idList) {
        boolean b = iService.removeByIds(idList);
        return b ? ApiResult.success() : ApiResult.error();
    }

    /**
     * 通过id获取
     *
     * @param id
     * @return
     */
    @GetMapping("get/{id}")
    @Override
    public ApiResult getById(@PathVariable Serializable id) {
        return ApiResult.success(iService.getById(id));
    }

    /**
     * 条件查询、无条件查询所有
     *
     * @param current 1
     * @param size    10
     * @param t
     * @return
     */
    @GetMapping("list")
    @Override
    public ApiResult list(@RequestParam(required = false, defaultValue = "1") Integer current,
                          @RequestParam(required = false, defaultValue = "10") Integer size,
                          T t) {
        QueryWrapper<T> tQueryWrapper = new QueryWrapper<>();
        Map<String, Object> clowns = BeanUtil.beanToMap(t);
        clownCamelCase2UnderlineCase(clowns).forEach(tQueryWrapper::eq);
        IPage<T> ts = iService.page(new Page<>(current, size), tQueryWrapper);
        return ApiResult.success(ts);
    }

    /**
     * 分页模糊查询
     * clown一定要与类的属性名一致
     *
     * @param current 1
     * @param size    10
     * @param t
     * @return
     */
    @GetMapping("search")
    @Override
    public ApiResult search(@RequestParam(required = false, defaultValue = "1") Integer current,
                            @RequestParam(required = false, defaultValue = "10") Integer size,
                            T t) {
        QueryWrapper<T> tQueryWrapper = new QueryWrapper<>();
        Map<String, Object> clowns = BeanUtil.beanToMap(t);
        clownCamelCase2UnderlineCase(clowns).forEach(tQueryWrapper::like);
        IPage<T> re = iService.page(new Page<>(current, size), tQueryWrapper);
        return ApiResult.success(re);
    }


    /**
     * 驼峰字段转换下划线
     * todo 时间的转换
     */
    public static Map<String, Object> clownCamelCase2UnderlineCase(Map<String, Object> objectMap) {
        //字段驼峰转换下划线
        HashMap<String, Object> clownMap = new HashMap<>();
        if (objectMap == null) {
            return clownMap;
        }
        objectMap.forEach((k, v) -> {
            if (v != null) {
                String s = StrUtil.toUnderlineCase(k);
                if ("false".equalsIgnoreCase(v.toString())) v = false;
                if ("true".equalsIgnoreCase(v.toString())) v = true;
                clownMap.put(s, v);
            }
        });
        return clownMap;
    }

}